function ajaxSubmit(formId){
	$('input, option, checkbox, select, button, radio').removeClass("formError");
	$.ajax({
		url: $('#'+formId).attr('action'),
		type: 'POST',
		data: $('#'+formId).serializeArray(),
		success: ajaxReturn
	});
	return false;
}

function ajaxRemove(url,remove_message){
	if(window.confirm(remove_message)){
		$.ajax({
			url: url,
			type: 'GET',
			success: ajaxReturn
		});
	}
}

function ajaxReturn(jSonMsg){
	try{
		var response = eval('('+jSonMsg+')');
	} catch(e){}
			
	try{ 
		if(true == response.redirect){
			window.location.replace(response.url);
			return true;
		}
	} catch(e){}
			
	try{
		$.each(response.content, function(key,value){
			if("_external"==key){
				$.each(value,displayError);
			}else{
				displayError(key, value);
			}
		});
	}catch(e){}
}

function displayError(fieldId,message){
	alert(fieldId+' - '+message.toString());
	$('#'+fieldId).addClass("formError");
}

function loading(message){
	var header = $(document.createElement('div'));
	header.attr('class','popHeader');
	header.append(document.createTextNode(message));
	
	var img = $(document.createElement('img'));
	img.attr('alt','loading');
	img.attr('src','static/images/ajax-loader.gif');
	
	var pop = $(document.createElement('div'));
	pop.attr('id','pop');
	pop.append(header);
	pop.append(img);
	
	var fade = $(document.createElement('div'));
	fade.attr('id','fade');
	fade.attr('class','overlay');
	
	$(document.body).append(pop);
	$(document.body).append(fade);
	$(".overlay").css({"width":$(document).width(),"height":$(document).height()});
}

function removeLoading(){
	$('#pop').remove();
	$('#fade').remove();
}

function file_uploaded(field,file){
	$('#'+field).val(file);
	try{
		$('#img_'+field).attr("src", URL_ROOT+file+'?'+Math.random());
	}catch(e){alert("Erro!");}
}

function get_highest_zIndex(){
    var elements = document.getElementsByTagName("*");
    var highest_index = 0;

    for (var i = 0; i < elements.length - 1; i++) {
        if (parseInt(elements[i].style.zIndex) > highest_index) {
            highest_index = parseInt(elements[i].style.zIndex);
        }
    }
    return highest_index;
}
function session_expired_test(json_return_message){
    //testa  se a sessao esta expirada
    try{
       var json = JSON.parse(json_return_message);
       if(json.redirect == true){
           alert("Sessão Expirada!");
           window.location.reload();
       }
    }catch(e){}
}    
function str_replace(chars,repls,str) {
	if (chars instanceof Array) {
		var arrString = new Array();
		for (i=0; i<chars.length; i++) {
			 var count = i-1;
			 if (i>0) {
				 arrString.push(arrString[count].replace(chars[i],repls[i]));
			 } else {
				 arrString.push(str.replace(chars[i],repls[i]));
			 }
		}
		string = arrString.pop();
	} else {
		string = str.replace(chars,repls);
	}
	return string;
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
//check if string is positive integer
function isNormalInteger(str) { 
    var n = ~~Number(str);
    return String(n) === str && n >= 0;
}
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}
function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}
function number_format (number, decimals, dec_point, thousands_sep) {
	number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');}
    return s.join(dec);
}
//parseTime("12:00 AM"); // {hh:  0, mm: 0}
//parseTime("12:00 PM"); // {hh: 12, mm: 0}
//parseTime("01:00 PM"); // {hh: 13, mm: 0}
//parseTime("23:00");    // {hh: 23, mm: 0}
function parseTime(s) {
    var part = s.match(/(\d+):(\d+)(?: )?(am|pm)?/i);
    var hh = parseInt(part[1], 10);
    var mm = parseInt(part[2], 10);
    var ap = part[3] ? part[3].toUpperCase() : null;
    if (ap === "AM") {
        if (hh == 12) {
            hh = 0;
        }
    }
    if (ap === "PM") {
        if (hh != 12) {
            hh += 12;
        }
    }
    return { hh: hh, mm: mm };
}

//input: n number
function isInt(n) {
   return n % 1 === 0;
}

//input: n string
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}